<template>
  <view class="detail-container">
    <!-- 加载中提示 -->
    <view class="loading-container" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 内容区域 -->
    <scroll-view 
      class="content-scroll" 
      scroll-y 
      v-if="!loading && post"
      :scroll-into-view="scrollToCommentId"
      @scrolltolower="handleScrollToLower"
    >
      <!-- 动态内容区域 -->
      <post-content 
        :post="post" 
        :is-owner="isOwner"
        @user-click="goToUserPage"
        @image-preview="previewImage"
        @like-click="toggleLike"
        @comment-click="focusCommentInput"
        @delete-click="handleDelete"
      />
      
      <!-- 评论区域 -->
      <comment-section 
        :comments="comments" 
        :has-more="hasMoreComments"
        @load-more="loadMoreComments"
      />
      
      <!-- 底部留白空间，防止内容被评论输入框遮挡 -->
      <view class="bottom-space"></view>
    </scroll-view>
    
    <!-- 评论输入组件 -->
    <comment-input 
      v-model:content="commentContent"
      v-model:isAnonymous="isAnonymous"
      :disabled="!canComment"
      @submit="submitComment"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onActivated } from 'vue';
import { useStore } from 'vuex';

// 导入自定义组件
import PostContent from '../../components/community/PostContent.vue';
import CommentSection from '../../components/community/CommentSection.vue';
import CommentInput from '../../components/community/CommentInput.vue';

const store = useStore();

// 获取页面参数
const postId = ref(null);
// 评论数据
const comments = ref([]);
const hasMoreComments = ref(false);

onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.id) {
    postId.value = options.id;
    fetchPostData();
    fetchComments(true);
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 动态详情 - 使用ref而非computed避免只读问题
const post = ref(null);

// 评论列表
const commentList = computed(() => store.getters['community/commentList']);

// 评论数量
const commentCount = computed(() => post.value ? post.value.commentsCount : 0);

// 是否是动态所有者
const isOwner = computed(() => {
  if (!post.value) return false;
  // 假设当前用户ID为1
  return post.value.userId === 1 && !post.value.isAnonymous;
});

// 加载状态 - 使用ref而非computed避免只读问题
const loading = ref(false);
const commentLoading = ref(false);

// 是否正在刷新
const refreshing = ref(false);

// 评论内容
const commentContent = ref('');

// 是否匿名评论
const isAnonymous = ref(false);

// 是否可以评论
const canComment = computed(() => {
  return !loading.value && post.value;
});

// 滚动到评论ID
const scrollToCommentId = ref('');

// 获取帖子数据
const fetchPostData = async () => {
  loading.value = true;
  
  try {
    await store.dispatch('community/fetchPostDetail', postId.value);
    post.value = store.getters['community/currentPost'];
  } catch (error) {
    console.error('获取帖子详情失败', error);
    uni.showToast({
      title: '获取帖子详情失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 获取评论列表
const fetchComments = async (refresh = false) => {
  if (!post.value) return;
  
  try {
    await store.dispatch('community/fetchCommentList', {
      postId: post.value.id,
      refresh
    });
    
    comments.value = store.getters['community/commentList'];
    hasMoreComments.value = store.getters['community/pagination'].hasMore;
  } catch (error) {
    console.error('获取评论列表失败', error);
  }
};

// 加载更多评论
const loadMoreComments = async () => {
  if (!hasMoreComments.value || !post.value) return;
  
  try {
    await store.dispatch('community/fetchCommentList', {
      postId: post.value.id,
      loadMore: true
    });
    
    comments.value = store.getters['community/commentList'];
    hasMoreComments.value = store.getters['community/pagination'].hasMore;
  } catch (error) {
    console.error('加载更多评论失败', error);
    uni.showToast({
      title: '加载更多评论失败，请重试',
      icon: 'none'
    });
  }
};

// 页面加载时获取帖子和评论数据
onMounted(async () => {
  await fetchPostData();
  await fetchComments();
});

// 页面激活时刷新数据
onActivated(async () => {
  await fetchPostData();
  await fetchComments(true);
});

// 处理滚动到底部事件
const handleScrollToLower = () => {
  if (hasMoreComments.value) {
    loadMoreComments();
  }
};

// 预览图片
const previewImage = (index) => {
  if (!post.value || !post.value.images) return;
  
  uni.previewImage({
    urls: post.value.images,
    current: post.value.images[index]
  });
};

// 点赞/取消点赞
const toggleLike = async () => {
  if (!post.value) return;
  
  const isLike = !post.value.isLiked;
  
  try {
    await store.dispatch('community/likePost', {
      postId: post.value.id,
      isLike
    });
    
    // 更新帖子数据
    await fetchPostData();
  } catch (error) {
    console.error('点赞操作失败', error);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 聚焦评论输入框
const focusCommentInput = () => {
  // 直接使用组件的v-model，不需要额外处理
};

// 删除帖子
const handleDelete = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条动态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await store.dispatch('community/deletePost', postId.value);
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          console.error('删除帖子失败', error);
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 提交评论
const submitComment = async () => {
  if (!canComment.value || !post.value || !commentContent.value.trim()) return;
  
  try {
    await store.dispatch('community/createComment', {
      postId: post.value.id,
      content: commentContent.value,
      isAnonymous: isAnonymous.value
    });
    
    // 清空评论内容
    commentContent.value = '';
    
    // 刷新评论列表
    await fetchComments(true);
    
    // 更新帖子评论数
    await fetchPostData();
  } catch (error) {
    console.error('发表评论失败', error);
    uni.showToast({
      title: '发表评论失败，请重试',
      icon: 'none'
    });
  }
};

// 跳转到用户主页
const goToUserPage = () => {
  if (!post.value) return;
  
  // 如果是匿名发布，不跳转
  if (post.value.isAnonymous) {
    return;
  }
  
  uni.navigateTo({
    url: `/pages/community/user?id=${post.value.userId}`
  });
};
</script>

<style lang="scss" scoped>
.detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
  position: relative;
  
  .loading-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .loading-text {
      font-size: 15px;
      color: #999999;
    }
  }
  
  .content-scroll {
    flex: 1;
    padding-bottom: 10px;
  }
  
  .bottom-space {
    height: 70px;
  }
}

.post-card {
  margin: 16px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.comment-section {
  margin: 0 16px 16px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background-color: #ffffff;
  
  .section-header {
    padding: 18px 20px;
    border-bottom: 1px solid #f5f5f5;
    
    .section-title {
      font-size: 17px;
      font-weight: 600;
      color: #333333;
      display: flex;
      align-items: center;
      
      &:before {
        content: '';
        width: 4px;
        height: 18px;
        background-color: #007aff;
        margin-right: 10px;
        border-radius: 2px;
      }
    }
  }
  
  .comment-list {
    .list-footer {
      text-align: center;
      padding: 16px 0;
      font-size: 14px;
      color: #007aff;
      border-top: 1px solid #f5f5f5;
      
      &:active {
        background-color: #f5f5f5;
      }
    }
  }
  
  .empty-comment {
    padding: 40px 20px;
    text-align: center;
    
    .empty-text {
      font-size: 14px;
      color: #999999;
      line-height: 1.5;
    }
  }
}

.comment-input-area {
  display: flex;
  align-items: center;
  padding: 14px 20px;
  border-top: 1px solid #e8e8e8;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
  
  .input-wrapper {
    flex: 1;
    height: 44px;
    background-color: #f5f5f5;
    border-radius: 22px;
    padding: 0 18px;
    margin-right: 14px;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
    
    .comment-input {
      width: 100%;
      height: 100%;
      font-size: 15px;
    }
  }
  
  .anonymous-switch {
    display: flex;
    align-items: center;
    margin-right: 10px;
    
    text {
      font-size: 12px;
      color: #666666;
      margin-right: 4px;
    }
  }
  
  .send-btn {
    width: 78px;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-size: 16px;
    color: #ffffff;
    background-color: #007aff;
    border-radius: 22px;
    padding: 0;
    font-weight: 500;
    box-shadow: 0 3px 10px rgba(0, 122, 255, 0.3);
    
    &:disabled {
      background-color: #cccccc;
      box-shadow: none;
    }
    
    &:active {
      transform: scale(0.96);
      box-shadow: 0 1px 4px rgba(0, 122, 255, 0.2);
    }
  }
}
</style>
